<template>
  <div class="create-post-container">
    <el-card class="create-post-card">
      <template #header>
        <div class="card-header">
          <h2>发布新帖子</h2>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="postForm" 
        :rules="rules" 
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="postForm.title" 
            placeholder="请输入帖子标题（5-50字）" 
            maxlength="50" 
            show-word-limit
          ></el-input>
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select 
            v-model="postForm.category" 
            placeholder="请选择帖子分类"
            style="width: 100%"
          >
            <el-option 
              v-for="item in categories" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="postForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或创建标签（最多5个）"
            style="width: 100%"
            :max="5"
          >
            <el-option
              v-for="item in tags"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入帖子内容（10-5000字）"
            maxlength="5000"
            show-word-limit
          ></el-input>
        </el-form-item>
        
        <el-form-item label="上传图片（可选）">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="9"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <el-icon><plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            支持jpg、png格式，单张不超过5MB，最多上传9张
          </div>
        </el-form-item>
        
        <el-form-item>
          <div class="form-actions">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitPost" :loading="submitting">
              发布帖子
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const router = useRouter();
const formRef = ref(null);
const submitting = ref(false);

// 表单数据
const postForm = reactive({
  title: '',
  category: '',
  tags: [],
  content: '',
  images: []
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在5-50个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择帖子分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '内容长度应在10-5000个字符之间', trigger: 'blur' }
  ]
};

// 分类选项
const categories = [
  { value: 'discussion', label: '讨论' },
  { value: 'question', label: '问答' },
  { value: 'share', label: '分享' },
  { value: 'suggestion', label: '建议' },
  { value: 'notice', label: '公告' }
];

// 标签选项
const tags = [
  { value: 'technology', label: '技术' },
  { value: 'life', label: '生活' },
  { value: 'work', label: '工作' },
  { value: 'study', label: '学习' },
  { value: 'entertainment', label: '娱乐' },
  { value: 'game', label: '游戏' },
  { value: 'sports', label: '体育' },
  { value: 'travel', label: '旅行' },
  { value: 'food', label: '美食' }
];

// 处理图片上传
const handleImageChange = (file) => {
  // 检查文件类型
  const isImage = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
  // 检查文件大小
  const isLt5M = file.raw.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传JPG或PNG格式的图片!');
    return false;
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  
  // 在实际项目中，这里应该将图片添加到表单数据中
  postForm.images.push(file);
  return true;
};

// 处理图片移除
const handleImageRemove = (file) => {
  const index = postForm.images.findIndex(item => item.uid === file.uid);
  if (index !== -1) {
    postForm.images.splice(index, 1);
  }
};

// 提交帖子
const submitPost = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    submitting.value = true;
    try {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('帖子发布成功');
        router.push('/community');
        submitting.value = false;
      }, 1000);
      
      // 实际API调用应该类似：
      // 1. 先上传图片（如果有）
      // const uploadedImages = await Promise.all(postForm.images.map(async (file) => {
      //   const formData = new FormData();
      //   formData.append('file', file.raw);
      //   const res = await request.post('/api/upload', formData);
      //   return res.url;
      // }));
      
      // 2. 然后提交帖子数据
      // await request.post('/api/posts', {
      //   title: postForm.title,
      //   category: postForm.category,
      //   tags: postForm.tags,
      //   content: postForm.content,
      //   images: uploadedImages
      // });
    } catch (error) {
      console.error('发布帖子失败:', error);
      ElMessage.error('发布帖子失败，请稍后重试');
      submitting.value = false;
    }
  });
};

// 返回上一页
const goBack = () => {
  ElMessageBox.confirm('确定要放弃编辑吗？未保存的内容将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.go(-1);
  }).catch(() => {});
};
</script>

<style scoped>
.create-post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.create-post-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>